<template>
<div>

</div>
</template>

<script>

import { doAuthorize } from '@/api/login'
import { aesDecrypt } from '@/utils/ase'
import { setToken, removeToken, removePassword, removeRememberMe, removeTenantId, removeTenantName, removeUsername } from '@/utils/auth'
import { Loading } from 'element-ui';
import store from '@/store'
import router from '@/router'

export default {
  name: "Login",
  data() {
    return {
      aesKey: 'JPlat',
      loadingInstance: undefined,
      params: { // URL 上的 client_id、scope 等参数
        clientId: undefined,
        clientSecret: undefined,
        grantType: 'password',
        username: undefined,
        password: undefined,
        scopes: undefined, // 优先从 query 参数获取；如果未传递，从后端获取
      },
    };
  },
  created() {
    // 解析参数
    // 例如说【自动授权不通过】：client_id=default&redirect_uri=https%3A%2F%2Fwww.iocoder.cn&response_type=code&scope=user.read%20user.write
    // 例如说【自动授权通过】：client_id=default&redirect_uri=https%3A%2F%2Fwww.iocoder.cn&response_type=code&scope=user.read
    this.params.client_id = this.$route.query.clientId
    this.params.client_secret = this.$route.query.clientSecret
    this.params.grant_type = this.$route.query.grantType
    this.params.username = this.$route.query.username
    this.params.password = this.$route.query.password
    this.params.scopes = this.$route.query.scope
    this.doAuthorizeFun();
  },
  methods: {
    doAuthorizeFun() {
      //账号、密码解密
      //this.params.username = aesDecrypt(this.params.username, this.aesKey)
      //this.params.password = aesDecrypt(this.params.password, this.aesKey)
      // 请求授权
      let loadingInstance = Loading.service({
        text: '授权登录中...'
      });
      removeUsername();
      removePassword();
      removeToken();
      removeTenantId();
      removeTenantName();
      removeRememberMe();
      this.$store.dispatch("Login", this.params).then(() => {
        this.$store.dispatch("GetInfo").then(() => {
          // 触发 GenerateRoutes 事件时，将 menus 菜单树传递进去
          store.dispatch('GenerateRoutes', userInfo.menus).then(accessRoutes => {
            // 根据 roles 权限生成可访问的路由表
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
        })
      }).catch(() => {
      });
      setTimeout(() => {
        this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
          loadingInstance.close();
          this.$router.push({path: this.redirect || "/"});
        });
      }, 3000);


    }
  }
};
</script>
